<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Model;
use think\Db;
use Exception;
class SalesInvoicing extends Model
{

    // 表名
    protected $name = 'kuyou_sales_invoicing_log';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit,$sort_field,$sort_type){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->page($page,$limit)->field("id,customers_id,bill_codes,money,tax,real_money,status,pay_money,invoice,invoice_header,FROM_UNIXTIME(times,'%Y-%m-%d') as times")->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->field("id,customers_id,bill_codes,money,tax,real_money,status,pay_money,invoice,invoice_header,FROM_UNIXTIME(times,'%Y-%m-%d') as times")->select())->toArray();
        }
        $customersModel = new Customers();
        foreach ($list as $list_k=>$list_v){
            $customers = $customersModel->where(['id'=>$list_v['customers_id']])->field('customer_code,customer_name')->find();
            if($customers){
                $list[$list_k]['customer_code'] = $customers['customer_code'];
                $list[$list_k]['customer_name'] = $customers['customer_name'];
            }else{
                $list[$list_k]['customer_code'] = '';
                $list[$list_k]['customer_name'] = '';
            }
            
            $code = Db::name('kuyou_goods_sales')->where(['purchase_code'=>$list_v['bill_codes']])->value('id');
            if($code){
                $list[$list_k]['code_type'] = 1;
            }else{
                $list[$list_k]['code_type'] = 2;
            }
        }

        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取可开票记录
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getInvoicing($where,$page,$limit){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = Db::name('kuyou_sales_invoicing')
                ->where($where)
                ->page($page,$limit)
                ->field("id,customers_id,bill_codes,money,tax,real_money,status,pay_money,give_money,invoice_status,FROM_UNIXTIME(bill_time,'%Y-%m-%d') as bill_time")
                ->select();
        }else{
            $list = Db::name('kuyou_sales_invoicing')
                ->where($where)
                ->field("id,customers_id,bill_codes,money,tax,real_money,status,pay_money,give_money,invoice_status,FROM_UNIXTIME(bill_time,'%Y-%m-%d') as bill_time")
                ->select();
        }
        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['customer_name'] = (new Customers())->where(['id'=>$list_v['customers_id']])->value('customer_name');
        }

        $count = Db::name('kuyou_sales_invoicing')
            ->where($where)->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'invoice|发票号'=>'require',
                'invoice_header|发票抬头'=>'require',
                'times|开票时间'=>'require',
                'invoice_data|开票数据'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $detail['invoice_data'] = (array)json_decode($detail['invoice_data'], true);

                $log = [];
                foreach ($detail['invoice_data'] as $params_k=>$params_v){
                    $row = Db::name('kuyou_sales_invoicing')->where(['id'=>$params_v['invoicing']])->find();
                    if(empty($row)){
                        return ['status'=>500,'msg'=>'开票数据查询错误'];
                    }else if(empty($params_v['pay_money'])){
                        return ['status'=>500,'msg'=>$row['bill_codes'].'请输入'.$row['bill_codes'].'开票金额'];
                    }else if(!is_numeric($params_v['pay_money'])){
                        return ['status'=>500,'msg'=>$row['bill_codes'].''.$row['bill_codes'].'开票金额格式不正确'];
                    }else{
                        $row['createtime'] = time();
                        $row['invoicing'] = $row['pay_money']+$params_v['pay_money'];
                        $row['give_money'] = $row['give_money']-$params_v['pay_money'];
                        $row['pay_money'] = $params_v['pay_money'];
                        $row['times'] = strtotime($detail['times']);
                        $row['invoice'] = $detail['invoice'];
                        $row['invoice_header'] = $detail['invoice_header'];
                        $log[] = $row;
                    }
                }
                $count = 0;
                Db::startTrans();
                try {
                    foreach ($log as $log_k=>$log_v){
                        $id = $log_v['id'];
                        Db::name('kuyou_sales_invoicing')->where(['id'=>$id])->update([
                            'invoice_status'=>1,
                            'pay_money'=>$log_v['invoicing'],
                            'give_money'=>$log_v['give_money']
                        ]);
                        unset($log_v['id']);unset($log_v['invoice_status']);unset($log_v['invoicing']);
                        $log_v['invoicing_id'] = $id;
                        $count += Db::name('kuyou_sales_invoicing_log')->insert($log_v);
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    return ['status'=>500,'msg'=>$e->getMessage()];
                }
                if($count){
                    return ['status'=>200,'msg'=>$count];
                }else{
                    return ['status'=>500,'msg'=>'添加失败'];
                }
            }
        }
    }

    /**
     * 删除
     * @param int $id
     * @return array
     */
    public static function delDetail($id){
        if(empty($id)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $ids = explode(',',$id);
            $list = (new SalesInvoicing())->where(['id'=>['in',$ids]])->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $row = Db::name('kuyou_sales_invoicing')->where(['id'=>$v['invoicing_id']])->find();
                    if($row){
                        Db::name('kuyou_sales_invoicing')->where(['id'=>$v['invoicing_id']])->update([
                            'invoice_status'=>'0',
                            'pay_money'=>($row['pay_money']-$v['pay_money']),
                            'give_money'=>($row['give_money']+$v['pay_money'])
                        ]);
                    }
                    $count += Db::name('kuyou_sales_invoicing_log')->where(['id'=>$v['id']])->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if($count){
                return ['status'=>200,'msg'=>$count];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }
}
